﻿using ConfExpert.Forms.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using DevTeam;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraEditors;
using System.Xml;
using System.IO;
using DevExpress.XtraEditors.Repository;

namespace ConfExpert.Forms.Depo
{
    public partial class StokDuzenleme : XForm
    {
        
        public StokDuzenleme()
        {
            InitializeComponent();
        }

        private void StokDuzenleme_Load(object sender, EventArgs e)
        {
            this.Text = "Stok Düzenleme";

            beiCustomer.Edit.Assign(RI(Rp.Vendor));

            gridView1.Init("StokDuzenleme", beiCustomer.EditValue.ToInt(), beiComboBox.EditValue.ToStr());
            gridView1.AddDetailGrid(gridView2, "OnAdGizli");

            beiCustomer.EditValueChanged += beiCustomer_EditValueChanged;

            gridView1.MakeReadOnly("OnAd");
            gridView1.MakeColumnInvisible("KVendorId", "KCustomerId", "OnAdGizli");
            gridView2.MakeColumnInvisible("ProductId", "KVendorId", "KCustomerId", "OnAd");
            gridView2.MakeColumnsReadOnly("KVendorId");
            gridView1.SetCaptions("OnAd:Kalite+DesenNo");
            gridView1.AddSummary("Sayi");

            ((RepositoryItemComboBox)beiComboBox.Edit).Items.Add("Üretici Kodu");
            ((RepositoryItemComboBox)beiComboBox.Edit).Items.Add("Müşteri Kodu");

            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            beiComboBox.EditValueChanged += beiComboBox_EditValueChanged;

            gridView1.BestFitColumns();
            gridView2.BestFitColumns();

        }


        void beiComboBox_EditValueChanged(object sender, EventArgs e)
        {
            if (beiComboBox.EditValue.Equals("Üretici Kodu"))
            {
                //beiCustomer.Caption = "  Üretici Kodu";
                beiCustomer.Edit.Assign(RI(Rp.Vendor));
                beiCustomer.EditValue = null;
            }
            else if (beiComboBox.EditValue.Equals("Müşteri Kodu"))
            {
                //beiCustomer.Caption = "Müşteri Kodu";
                beiCustomer.Edit.Assign(RI(Rp.V_Customer));
                beiCustomer.EditValue = null;
            }

        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gridView2.BestFitColumns();
        }

        void beiCustomer_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.RefreshDataSource("StokDuzenleme", beiCustomer.EditValue.ToInt(), beiComboBox.EditValue.ToStr());
           // GridView1AfterInit = gridView1.DataTable();
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
        }

        private void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            gridView2.EndEditing();

            string xml = gridView2.SerializeChanges();
            DataSet d = new DataSet();
            XmlReader xmlReader = XmlReader.Create(new StringReader(xml));
            d.ReadXml(xmlReader);
            if (d.Tables.Count > 0 && d.Tables[0] != null)
            {
                DataTable DegisenSatirlar = d.Tables[0];

                DataColumnCollection columns = DegisenSatirlar.Columns;

                if (!columns.Contains("Name"))
                {
                    DegisenSatirlar.Columns.Add("Name");
                }
                //DataTable dtGridView1 = gridView1.DataTable();
                for (int i = 0; i < DegisenSatirlar.Rows.Count; ++i)
                {
                    DegisenSatirlar.Rows[i]["Name"] = DegisenSatirlar.Rows[i]["OnAd"].ToStr() + (DegisenSatirlar.Rows[i]["Name"].ToStr().Equals(String.Empty) ? String.Empty : '/' + DegisenSatirlar.Rows[i]["Name"].ToStr());
                }


                ExecuteNonQuery("UpdProduct2", DegisenSatirlar.Serialize());
            }

            string xml2 = gridView1.SerializeChanges();
            DataSet d2 = new DataSet();
            XmlReader xmlReader2 = XmlReader.Create(new StringReader(xml2));
            d2.ReadXml(xmlReader2);

            if (d2.Tables.Count > 0 && d2.Tables[0] != null)
            {
                DataTable DegisenSatirlar2 = d2.Tables[0];
                DataTable dtGridView2 = gridView2.DataTable();
                DataTable dtDegisikliklerUpdate = new DataTable();
                dtDegisikliklerUpdate.Clear();
                dtDegisikliklerUpdate.Columns.Add("ProductId", typeof(int));
                dtDegisikliklerUpdate.Columns.Add("Name", typeof(string));

                for (int j = 0; j < DegisenSatirlar2.Rows.Count; ++j)
                {
                    if (!DegisenSatirlar2.Rows[j]["OnAd"].ToStr().Equals(DegisenSatirlar2.Rows[j]["OnAdGizli"].ToStr()))
                    {
                        for (int k = 0; k < dtGridView2.Rows.Count; ++k)
                        {
                            if (dtGridView2.Rows[k]["OnAd"].ToStr().Equals(DegisenSatirlar2.Rows[j]["OnAdGizli"].ToStr()))
                            {
                                DataRow NewRow = dtDegisikliklerUpdate.NewRow();
                                NewRow["ProductId"] = dtGridView2.Rows[k]["ProductId"].ToInt();
                                NewRow["Name"] = DegisenSatirlar2.Rows[j]["OnAd"].ToStr() + (dtGridView2.Rows[k]["Name"].ToStr().Equals(String.Empty) ? String.Empty : '/' + dtGridView2.Rows[k]["Name"].ToStr());
                                dtDegisikliklerUpdate.Rows.Add(NewRow);
                            }
                        }
                    }
                }
                ExecuteNonQuery("UpdProduct4", dtDegisikliklerUpdate.Serialize());
            }
                Rfrsh();
            
        }

        private void bbiMetinKopyala_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string FieldName = String.Empty,
                   Temp = String.Empty,
                   SelectedValues = String.Empty;

            GridCell[] gcArray = gridView2.GetSelectedCells();
            if (gcArray.Length > 0)
            {
                for (int i = 0; i < gcArray.Length; ++i)
                {
                    if (i == 0)
                        Temp = gcArray[0].Column.FieldName;
                    else
                    {
                        FieldName = gcArray[i].Column.FieldName;
                        if (!FieldName.Equals(Temp))
                        {
                            XtraMessageBox.Show("Tabloda farklı sütunlardan seçim yaptınız. Lütfen seçiminizi tek bir sütun üzerinde yapınız.", "Uyarı");
                            return;
                        }
                    }

                }
            }
            else
            {
                XtraMessageBox.Show("Tablodan seçim yapmadınız.", "Uyarı");
                return;
            }

            if (gcArray[0].Column.FieldName.Equals("Name") || gcArray[0].Column.FieldName.Equals("KVendorId"))
            {
                XtraMessageBox.Show("Bu sütunda metin kopyalama yapamazsınız.", "Uyarı");
                return;
            }

            SelectedValues = gridView2.GetSelectedValues(gcArray[0].Column.FieldName);

            string[] SelectedValuesArray = SelectedValues.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            string TempStr = String.Empty;

            if (SelectedValuesArray.Length > 0)
            {
                for (int j = 0; j < SelectedValuesArray.Length; ++j)
                {
                    if (j == 0)
                        TempStr = SelectedValuesArray[0];
                    else
                    {
                        if (!SelectedValuesArray[j].Equals(TempStr))
                        {
                            XtraMessageBox.Show("Yaptığınız seçim tek bir özgün metin değeri içermeli.", "Uyarı");
                            return;
                        }
                    }
                }
            }
            else
            {
                XtraMessageBox.Show("Seçiminizin tamamı boş hücrelerden oluşmamalı.", "Uyarı");
                return;
            }

            int[] SelectedRowHandles = gridView2.GetSelectedRows();
            int ProductId, IntAlan = 0, CheckIntAlan = 0;
            string StringAlan = String.Empty, CheckStringAlan = String.Empty;
            bool StringDegerMi = (gcArray[0].Column.FieldName.Equals("Konstruksiyon") || gcArray[0].Column.FieldName.Equals("KaliteAciklama")) ? true : false;
            bool BosHucreYok = true;

            DataTable dtUpdate = new DataTable();
            dtUpdate.Clear();
            dtUpdate.Columns.Add("ProductId", typeof(int));
            dtUpdate.Columns.Add("IntAlan", typeof(int));
            dtUpdate.Columns.Add("StringAlan", typeof(string));

            for (int h = 0; h < SelectedRowHandles.Length; ++h)
            {
                if (StringDegerMi)
                {
                    StringAlan = gridView2.GetRowCellValue(SelectedRowHandles[h], gcArray[0].Column.FieldName).ToStr();
                    if (StringAlan != null && !StringAlan.Equals(String.Empty))
                        break;
                }
                else
                {
                    IntAlan = gridView2.GetRowCellValue(SelectedRowHandles[h], gcArray[0].Column.FieldName).ToInt();
                    if (IntAlan > 0)
                        break;
                }
            }

            for (int k = 0; k < SelectedRowHandles.Length; ++k)
            {
                ProductId = gridView2.GetRowCellValue(SelectedRowHandles[k], "ProductId").ToInt();
                if (StringDegerMi)
                {
                    DataRow NewRow = dtUpdate.NewRow();
                    NewRow["ProductId"] = ProductId;
                    NewRow["StringAlan"] = StringAlan;
                    dtUpdate.Rows.Add(NewRow);

                    CheckStringAlan = gridView2.GetRowCellValue(SelectedRowHandles[k], gcArray[0].Column.FieldName).ToStr();
                    if (CheckStringAlan == null || CheckStringAlan.Equals(String.Empty))
                        BosHucreYok = false;
                }
                else
                {
                    DataRow NewRow = dtUpdate.NewRow();
                    NewRow["ProductId"] = ProductId;
                    NewRow["IntAlan"] = IntAlan;
                    dtUpdate.Rows.Add(NewRow);

                    CheckIntAlan = gridView2.GetRowCellValue(SelectedRowHandles[k], gcArray[0].Column.FieldName).ToInt();
                    if (CheckIntAlan == 0)
                        BosHucreYok = false;
                }
            }
            //gridView2.GetSelectedValues("ProductId");

            if (BosHucreYok)
            {
                XtraMessageBox.Show("Seçiminizde en az bir boş hücre olmalı.", "Uyarı");
                return;
            }

            /*ExecuteNonQuery("UpdProduct3", dtUpdate.Serialize(), StringDegerMi, gcArray[0].Column.FieldName);
            Rfrsh();*/
            for (int p = 0; p < SelectedRowHandles.Length; ++p)
            {
                if (StringDegerMi)
                {
                    gridView2.SetRowCellValue(SelectedRowHandles[p], gcArray[0].Column.FieldName, StringAlan);
                }
                else
                {
                    gridView2.SetRowCellValue(SelectedRowHandles[p], gcArray[0].Column.FieldName, IntAlan);
                }
            }

        }

        private void Rfrsh()
        {
            gridView1.EndEditing();
            gridView2.EndEditing();
            int RowHandle1 = gridView1.FocusedRowHandle;

            gridView1.RefreshDataSource("StokDuzenleme", beiCustomer.EditValue.ToInt(), beiComboBox.EditValue.ToStr());
            gridView1.ClearSelection();
            gridView1.FocusedRowHandle = RowHandle1;
            gridView1.SelectRow(RowHandle1);

            //GridView1AfterInit = gridView1.DataTable();

            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
        }

        /*private void SetGridView1AfterInit()
        {
            DataTable dtGV1 = gridView1.DataTable();

            if (GridView1AfterInit == null)
            {
                GridView1AfterInit = new DataTable();
                GridView1AfterInit.Clear();
                GridView1AfterInit.Columns.Add("OnAd", typeof(string));
                GridView1AfterInit.Columns.Add("RowHandle", typeof(int));
            }

            for(int i = 0; i < dtGV1.Rows.Count; ++i)
            {
                DataRow NewRow = GridView1AfterInit.NewRow();
                NewRow["OnAd"] = dtGV1.Rows[i]["OnAd"].ToStr();
                NewRow["RowHandle"] = gridView1.FocusedRowHandle; // BOYLE OLMAYACAK
                GridView1AfterInit.Rows.Add(NewRow);
            }
        }*/
    }
}
